﻿using B.S.DataBase.MyProject.Domain.RBAC;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using B.S.DataBase.MyRead.API.Appicant.Command.Users;
using B.S.DataBase.MyRead.API.Common;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace B.S.DataBase.MyRead.API.Appicant.CommandHandler.Users
{
    public class LoginCommandHandler : IRequestHandler<LoginCommand, APIResult<User>>
    {
        private readonly IBaseRepository<User> userRepos;
        private readonly IConfiguration config;
        public LoginCommandHandler(IBaseRepository<User> userRepos, IConfiguration config)
        {
            this.userRepos = userRepos;
            this.config = config;
        }


        public Task<APIResult<User>> Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            APIResult<User> result = new APIResult<User>();
            var login = userRepos.GetAll().Result.FirstOrDefault(x => x.UserName == request.UserName && x.Password == request.Password);
            if (login == null)
            {
                result.Code = APIEnum.登录失败密码或用户名错误;
                result.Msg = APIEnum.登录失败密码或用户名错误.ToString();
            }
            else
            {   
                result.Code = APIEnum.登录成功;
                result.Msg = APIEnum.登录成功.ToString();
                result.data = login;
            }
            //私钥
            //读取配置文件
            var jwtSettings = config.GetSection("JwtSettings").Get<JwtSettings>();
            var secretByte = Encoding.UTF8.GetBytes(jwtSettings.secretByte);
            // 非对称加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            // 使用256 生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            var claims = new[] {
               new Claim("UserName",login.UserName),
               new Claim("UserId",login.UserId.ToString())
           };
            // 生成Token
            var token = new JwtSecurityToken(
                issuer: jwtSettings.Issuer,
                audience: jwtSettings.Audience,
                expires: DateTime.Now.AddDays(1), // 一天后过期
                signingCredentials: signingCredentials,
                claims: claims
            );
            // 生成token 字符串
            var strToken = new JwtSecurityTokenHandler().WriteToken(token);
            result.token = strToken;
            return Task.FromResult(result);

        }
    }
}
